package com.zhongli.devplatform.controller.sys;

import com.zhongli.devplatform.dto.sys.MenuDTO;
import com.zhongli.devplatform.service.imp.common.ReadMenuService;
import com.zhongli.devplatform.vo.sys.MenuVO;
import com.zhongli.devplatform.bean.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/menu")
@CrossOrigin(maxAge = 3600)
public class MenuController {


    @Autowired
    private ReadMenuService menuService;

    @Autowired
    private CacheManager cacheManager;

    @Value("${dev-platform.cache-name}")
    private String cacheName;

    @RequestMapping("/loadCurrUserMenu")
    public Res loadCurrUserMenu(Integer roleId) {
        List<MenuVO> menus = (List<MenuVO>) cacheManager.getCache(cacheName + ReadMenuService.CACHE_KEY).get(roleId).get();
        return new Res(menus);
    }

    @RequestMapping("/list")
    public Res list() {
        return new Res(menuService.list());
    }

    @PostMapping("/save")
    public Res save(MenuDTO menuDTO) {
        menuService.save(menuDTO);
        return new Res(null);
    }

    @RequestMapping("/refreshCache")
    public Res refreshCache() {
        menuService.putCache();
        return new Res(null);
    }

    @RequestMapping("/delete")
    public Res delete(Integer id) {
        menuService.delete(id);
        return new Res(null);
    }

    @RequestMapping("/listMenuIdByRole")
    public Res listMenuIdByRole(Integer roleId) {
        return new Res(menuService.listMenuIdByRole(roleId));
    }


}
